import db_config from "../utils/db_config.js";
import Idb from 'idb-js'

export const imgUrl = "http://yuqian-imsdk.oss-cn-chengdu.aliyuncs.com/"

/** 
 * @method 准确条件查询本地数据库单个数据
 * @param db  需要操作的数据库
 * @param tableName  需要操作的表名
 * @param queryIndex  需要查询的索引名
 * @param queryIndexValue  对应索引名的值
 * @returns 
 */
export function queryIndexDB(db, tableName, queryIndex, queryIndexValue) {
  return new Promise((resolve, reject) => {
    var tx = db.transaction([tableName]);
    let store = tx.objectStore(tableName);
    var request = store
      .index(queryIndex) // 索引对象
      .openCursor(IDBKeyRange.only(queryIndexValue), "prev"); // 指针对象(倒序搜索)
    request.onsuccess = function (e) {
      if (e) {
        resolve(e)
      } else {
        reject(console.log("未查询到任何数据"))
      }
    }
  })
}
export function initIndexDB(dbName) {
  return new Promise((resolve, reject) => {
    let request = indexedDB.open(dbName);
    // err
    request.onerror = (event) => {
      reject("数据库打开/创建报错",)
    };
    // success
    request.onsuccess = (event) => {
      resolve(event.target.result)
    };
    request.onupgradeneeded = function (event) {
      let db = event.target.result
      console.log('数据库升级')
      let objectStoreMessage, objectStoreUsers, objectStoreMemorandum;
      if (!db.objectStoreNames.contains('account')) {
        objectStoreMessage = db.createObjectStore('account', { keyPath: 'id', autoIncrement: true });
      } else {
        objectStoreMessage = event.target.transaction.objectStore('account')
      }
      if (!db.objectStoreNames.contains('users')) {
        objectStoreUsers = db.createObjectStore('users', { keyPath: 'id', autoIncrement: true });
      } else {
        objectStoreUsers = event.target.transaction.objectStore('users')
      }
      if (!db.objectStoreNames.contains('memorandum')) {
        objectStoreMemorandum = db.createObjectStore('memorandum', { keyPath: 'id', autoIncrement: true });
      } else {
        objectStoreMemorandum = event.target.transaction.objectStore('memorandum')
      }
      objectStoreMessage.createIndex('id', 'id', { unique: true })
      objectStoreMessage.createIndex('time', 'time', { unique: false })
      objectStoreMessage.createIndex('name', 'name', { unique: false })
      objectStoreMessage.createIndex('category', 'category', { unique: false })
      objectStoreMessage.createIndex('industry', 'industry', { unique: false })
      objectStoreMessage.createIndex('notes', 'notes', { unique: false })
      objectStoreMessage.createIndex('money', 'money', { unique: false })
      objectStoreMessage.createIndex('yearMonth', 'yearMonth', { unique: false })
      objectStoreMessage.createIndex('cateAndYM', ['category', 'yearMonth'], { unique: false })
      objectStoreUsers.createIndex('id', 'id', { unique: true })
      objectStoreUsers.createIndex('number', 'number', { unique: true })
      objectStoreUsers.createIndex('password', 'password', { unique: false })
      objectStoreUsers.createIndex('numAndpwd', ['number', 'password'], { unique: false })
      objectStoreMemorandum.createIndex('id', 'id', { unique: true })
      objectStoreMemorandum.createIndex('time', 'time', { unique: false })
      objectStoreMemorandum.createIndex('content', 'content', { unique: false })
      objectStoreMemorandum.createIndex('name', 'name', { unique: false })
    }
  })
}
export function initIdb() {
  return new Promise((resolve, reject) => {
    Idb(db_config).then((res) => {
      resolve(res)
    });
  })
}
export function queryBoundIndexDB(data) {
  return new Promise((resolve, reject) => {
    var tx = data.db.transaction([data.tableName]);
    let store = tx.objectStore(data.tableName);
    var request = store
      .index(data.queryIndex) // 索引对象
      .openCursor(IDBKeyRange.bound(data.queryIndexValueStart, data.queryIndexValueEnd));
    request.onsuccess = function (e) {
      if (e) {
        resolve(e)
      } else {
        reject(console.log("未查询到任何数据"))
      }
    }
  })
}

/** 
 * @method 分页查询本地数据库
 * @param page 查询的页码
 * @param pageSize  每页查询的数量
 * @param db  需要操作的数据库
 * @param tableName  需要操作的表名
 * @param queryIndex  需要查询的索引名
 * @param queryIndexValue  对应索引名的值
 * @returns 
 */
export function queryIndexDBByPage(data) {
  return new Promise((resolve, reject) => {
    let page = data.page
    let pageSize = data.pageSize
    let list = [];
    let counter = 0; // 计数器
    let advanced = true; // 是否跳过多少条查询
    var tx = data.db.transaction([data.tableName]);
    let store = tx.objectStore(data.tableName);
    var request = store
      .index(data.queryIndex) // 索引对象
      .openCursor(IDBKeyRange.only(data.queryIndexValue),'prev'); // 指针对象(倒序搜索)
    request.onsuccess = function (e) {
      var cursor = e.target.result;
      if (page > 1 && advanced) {
        advanced = false;
        cursor.advance((page - 1) * pageSize); // 跳过多少条
        return;
      }
      if (cursor) {
        list.push(cursor.value);
        counter++;
        if (counter < pageSize) {
          cursor.continue(); // 遍历了存储对象中的所有内容
        } else {
          cursor = null;
          resolve(list)
        }
      } else {
        resolve(list)
      }
    };
    request.onerror = function (err) {
      reject(err)
    };
  })
}

/** 
 * @method 本地数据库模糊匹配分页查询
 * @param page 查询的页码
 * @param pageSize  每页查询的数量
 * @param db  需要操作的数据库
 * @param tableName  需要操作的表名
 * @param queryKey  需要模糊查询的条件  
 * @param key  模糊匹配的关键字
 * @returns 
 */
export function queryIndexDBVagueByPage(data) {
  return new Promise((resolve, reject) => {
    let page = data.page
    let pageSize = data.pageSize
    let list = [];
    let counter = 0; // 计数器
    let advanced = true; // 是否跳过多少条查询
    var tx = data.db.transaction([data.tableName]);
    let store = tx.objectStore(data.tableName);
    var request = store.openCursor(null,'prev');
    request.onsuccess = function (e) {
      var cursor = e.target.result;
      if (page > 1 && advanced) {
        advanced = false;
        cursor.advance((page - 1) * pageSize); // 跳过多少条
        return;
      }
      if (cursor) {
        if (cursor.value[data.queryKey] && cursor.value[data.queryKey].indexOf(data.key) != -1) {
          list.push(cursor.value);
          counter++;
        }
        if (counter < pageSize) {
          cursor.continue(); // 遍历了存储对象中的所有内容
        } else {
          cursor = null;
          resolve(list)
        }
      } else {
        resolve(list)
      }
    };
    request.onerror = function (err) {
      reject(err)
    };
  })
}

/** 
 * @method 分页复合查询本地数据库
 * @param page 查询的页码
 * @param pageSize  每页查询的数量
 * @param db  需要操作的数据库
 * @param tableName  需要操作的表名
 * @param compositeQueryIndex  需要查询的复合索引名
 * @param IndexValueOneStart  对应的第一个索引名的开始值
 * @param IndexValueOneEnd  对应的第一个索引名的结束值
 * @param IndexValueTwoStart  对应的第二个索引名的开始值
 * @param IndexValueTwoEnd  对应的第二个索引名的结束值
 * @returns 
 */
export function compositeQueryIndexDBByPage(data) {
  return new Promise((resolve, reject) => {
    let page = data.page
    let pageSize = data.pageSize
    let list = [];
    let counter = 0; // 计数器
    let advanced = true; // 是否跳过多少条查询
    var tx = data.db.transaction([data.tableName]);
    let store = tx.objectStore(data.tableName);
    var request = store
      .index(data.compositeQueryIndex) // 索引对象
      .openCursor(IDBKeyRange.bound([data.IndexValueOneStart, data.IndexValueTwoStart], [data.IndexValueOneEnd, data.IndexValueTwoEnd]), "prev");
    request.onsuccess = function (e) {
      var cursor = e.target.result;
      if (page > 1 && advanced) {
        advanced = false;
        cursor.advance((page - 1) * pageSize); // 跳过多少条
        return;
      }
      if (cursor) {
        list.push(cursor.value);
        counter++;
        if (counter < pageSize) {
          cursor.continue(); // 遍历了存储对象中的所有内容
        } else {
          cursor = null;
          resolve(list)
        }
      } else {
        resolve(list)
      }
    };
    request.onerror = function (err) {
      reject(err)
    };
  })
}

/** 
 * @method 查询单个复合索引查询
 * @param db  需要操作的数据库
 * @param tableName  需要操作的表名
 * @param compositeQueryIndex  需要查询的复合索引名
 * @param IndexValueOne  对应的第一个索引名的开始值
 * @param IndexValueTwo  对应的第二个索引名的开始值
 * @returns 
 */
export function compositeQuerySingleIndexDB(data) {
  return new Promise((resolve, reject) => {
    var tx = data.db.transaction([data.tableName]);
    let store = tx.objectStore(data.tableName);
    var request = store
      .index(data.compositeQueryIndex) // 索引对象
      .openCursor([data.IndexValueOne, data.IndexValueTwo]);
    request.onsuccess = function (e) {
      var cursor = e.target.result;
      resolve(cursor)
    };
    request.onerror = function (err) {
      reject(err)
    };
  })
}

/** 
 * @method 数组中对象去重
 * @param arr  需要去重的数组
 * @param key  需要判断的属性去重  
 * @returns 
 */
export function duplicateRemoval(arr,key) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i][key] == arr[j][key]) {
        arr.splice(j, 1)
        j--
      }
    }
  }
}

/** 
 * @method 触底加载下一页
 * @param element  需要监听滚动条位置的元素
 * @returns 
 */
export function observeScroll(element) {
  let isBottom = false
  element.addEventListener("scroll", (e) => {
    const scrollTop = element.scrollTop
    const windowHeight = element.clientHeight
    const scrollHeight = element.scrollHeight
    if (scrollTop + windowHeight >= scrollHeight - 20) {
      isBottom = true
    }
  });
}

/** 
 * @method 根据某个条件对数组进行排序
 * @param arr   需要排序的数组
 * @param key   按某个条件排序
 * @param type  0为从小到大排序，1则相反  
 * @returns 
 */
export function arrSort(arr, key, type) {
  if (type == 0) {
    for (let i = 0; i < arr.length; i++) {
      for (let j = i + 1; j < arr.length; j++) {
        if (arr[i][key] > arr[j][key]) {
          let template;
          template = arr[i]
          arr[i] = arr[j]
          arr[j] = template
        }
      }
    }
  } else {
    for (let i = 0; i < arr.length; i++) {
      for (let j = i + 1; j < arr.length; j++) {
        if (arr[i][key] < arr[j][key]) {
          let template;
          template = arr[i]
          arr[i] = arr[j]
          arr[j] = template
        }
      }
    }
  }
}

/** 
 * @method 获取时间格式化
 * @param  time   需要格式化的时间
 * @param  separator   年月日格式化后按某个符号分割
 * @returns 
 */
export function timeFormat(time, separator) {
  let date = new Date(time)
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()
  if (separator == undefined) {
    return `${year}年${month}月${day}日 ${hour}时${minute}分${second}秒`
  } else {
    return year + separator + month + separator + day + " " + hour + ":" + minute + ":" + second
  }
}